#include "GL/glew.h"
#include "LoadShader.h"
#include "utility.h"
#include "vmath.h"

extern int Width, Height;

GLuint tex2D, texCube;

GLuint program2D, programCube;
Model3D panel;

bool init()
{
	float texData[] = { 1.0, 0.0, 0.0, 1.0,
						0.0, 1.0, 0.0, 1.0,
						0.0, 0.0, 1.0, 1.0,
						1.0, 1.0 ,1.0, 1.0 };

	glGenTextures(1, &tex2D);
	glBindTexture(GL_TEXTURE_2D, tex2D);
	glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, 2, 2);
	glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 2, 2, GL_RGBA, GL_FLOAT, texData);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

	glGenTextures(1, &texCube);
	glBindTexture(GL_TEXTURE_CUBE_MAP, texCube);
	for (int i = 0; i < 6; ++i)
	{
		glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA8, 2, 2, 0, GL_RGBA, GL_FLOAT, texData);
	}
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

	ShaderInfo si2[] = { { GL_VERTEX_SHADER, "Texture2D.vert" },{ GL_FRAGMENT_SHADER, "Texture2D.frag" },{ GL_NONE, nullptr } };
	program2D = LoadShade(si2);

	ShaderInfo si3[] = { { GL_VERTEX_SHADER, "Cube.vert" },{ GL_FRAGMENT_SHADER, "Cube.frag" },{ GL_NONE, nullptr } };
	programCube = LoadShade(si3);

	panel = LoadPanel(0, -1, 1);


	glClearColor(0.0f, 0.05f, 0.05f, 1.0f);
	return true;
}

void Display(double time)
{
	glClear(GL_COLOR_BUFFER_BIT);

	glUseProgram(program2D);
	auto m = Matrix4f::createScale(0.003f, 0.003f*Width / Height, 0.0f);
	m = Matrix4f::createTranslation(-0.5f, 0.f, 0.f) * m;
	glUniformMatrix4fv(0, 1, GL_FALSE, m);
	glUniform1i(1, 0);
	glBindTexture(GL_TEXTURE_2D, tex2D);
	panel.Draw();
	glBindTexture(GL_TEXTURE_2D, 0);

	glUseProgram(programCube);
	m = Matrix4f::createTranslation(1.0f, 0.f, 0.f) * m;
	glUniformMatrix4fv(0, 1, GL_FALSE, m);
	glUniform1i(1, 0);
	glBindTexture(GL_TEXTURE_CUBE_MAP, texCube);
	panel.Draw();
	glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
}

void onClose()
{
	panel.deleteBuffer();
}

